package com.ttdevs.socket.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.concurrent.BlockingQueue;

import com.ttdevs.socket.ISocket;
import com.ttdevs.socket.util.BaseThread;
import com.ttdevs.socket.util.SocketConfig;

public class UDPReceiver extends BaseThread {

	private ISocket mSocket;
	private DatagramSocket mUDPSocket;
	private BlockingQueue<DatagramPacket> mReceiverQueue;
	private DatagramPacket receivePacket;

	public UDPReceiver(BlockingQueue<DatagramPacket> receiverQueue, ISocket socket, DatagramSocket udpSocket) {
		mSocket = socket;
		mReceiverQueue = receiverQueue;
		mUDPSocket = udpSocket;
		receivePacket = new DatagramPacket(new byte[SocketConfig.RECEIVERPACKETSIZE], SocketConfig.RECEIVERPACKETSIZE);
	}

	@Override
	public boolean prepare() {
		if (mSocket == null || mReceiverQueue == null || mUDPSocket == null) {
			return false;
		}
		return super.prepare();
	}

	@Override
	public void execute() {
		try {
			mUDPSocket.receive(receivePacket);
			mReceiverQueue.put(receivePacket);
		} catch (InterruptedException e) {
			e.printStackTrace();
			notifyError();
		} catch (IOException e) {
			e.printStackTrace();
			notifyError();
		}
	}

	private void notifyError() {
		mSocket.close(true, true);
		this.quit();
	}
}
